<template>
  <div>
    <el-select
      style="width: 30%"
      placeholder="请输入药品名称"
      v-model="searchValue"
      filterable
      default-first-option
      clearable
    >
      <el-option
        v-for="item in tableData"
        :key="item.id"
        :label="item.name"
        :value="item.name"
      ></el-option>
    </el-select>
    <el-button @click="searchButton">搜索</el-button>
    <el-button style="float: right; border-color: blue" @click="exportTable">导出</el-button>
    <el-button style="float: right" @click="[(dialogFormVisible = true), (isEdit = false)]"
      >增加库存</el-button
    >
  </div>
  <el-table :data="currentPageData" style="width: 100%">
    <el-table-column fixed prop="name" label="药品名称" />
    <el-table-column prop="categoryName" label="药品分类" />
    <el-table-column prop="price" label="药品价格" />
    <el-table-column prop="manufacturer" label="药品厂家" />
    <el-table-column prop="stock" label="药品库存" />
    <el-table-column prop="status" label="药品状态" />
    <el-table-column fixed="right" label="操作">
      <template #default="scope">
        <el-button link type="primary" size="small" @click="handleClick(scope.row)">
          编辑
        </el-button>
        <el-popconfirm
          :title="scope.row.status === '在售' ? '是否下架该药品' : '是否上架该药品'"
          @confirm="deleteCategory(scope.row)"
          confirm-button-text="确认"
          cancel-button-text="取消"
        >
          <template #reference>
            <el-button link type="primary" size="small">{{
              scope.row.status === '在售' ? '下架' : '上架'
            }}</el-button>
          </template>
        </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
    :current-page="currentPage"
    :page-size="pageSize"
    :page-sizes="[5, 10, 20, 50, 100]"
    layout="total,sizes, prev, pager, next,"
    :total="total"
    style="float: right"
  ></el-pagination>
  <el-dialog v-model="dialogFormVisible" title="增加库存" width="500">
    <el-form :model="form" label-width="15%">
      <el-form-item label="药品名称" :label-width="0">
        <el-input v-model="form.name" placeholder="请输入药品名称" autocomplete="off" />
      </el-form-item>
      <el-form-item label="标签名称" :label-width="0">
        <el-select
          v-model="form.categoryId"
          placeholder="请输入标签名称"
          filterable
          default-first-option
          clearable
        >
          <el-option
            v-for="option in options"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="药品价格" :label-width="0">
        <el-input v-model="form.price" placeholder="请输入药品价格" autocomplete="off" />
      </el-form-item>
      <el-form-item label="生产厂家" :label-width="0">
        <el-input v-model="form.manufacturer" placeholder="请输入生产厂家" autocomplete="off" />
      </el-form-item>
      <el-form-item label="进货数量" :label-width="0">
        <el-input v-model="form.stock" placeholder="请输入进货数量" autocomplete="off" />
      </el-form-item>
      <el-form-item label="有效期" :label-width="0">
        <el-input v-model="form.expirationDate" placeholder="请输入有效期" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogSure"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import myAxios from '../../axios/myAxios'
import { onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import ExcelJS from 'exceljs'
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)
const currentPageData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return tableData.value.slice(start, end)
})
const handleCurrentChange = (newPage: number) => {
  currentPage.value = newPage
}
const handleSizeChange = (newSize: number) => {
  pageSize.value = newSize
  currentPage.value = 1
}

const tableData = ref([])
const options = ref<[{ label: string; value: number }]>()
const nameOfId = ref<{ [key: number]: string }>({})
const form = reactive({
  name: '',
  categoryId: '',
  categoryName: '',
  price: '',
  manufacturer: '',
  stock: '',
  expirationDate: '',
  status: '',
})
const isEdit = ref(false)
const idForEdit = ref(0)
const dialogFormVisible = ref(false)
const dialogSure = () => {
  if (isEdit.value) {
    myAxios
      .put('/medicine/update', {
        id: idForEdit.value,
        name: form.name,
        categoryId: form.categoryId,
        price: form.price,
        manufacturer: form.manufacturer,
        stock: form.stock,
        expirationDate: form.expirationDate,
      })
      .then((res) => {
        if (res.data.code === 200) {
          ElMessage({
            message: '修改成功',
            type: 'success',
          })
          init()
        } else {
          ElMessage({
            message: '修改失败',
            type: 'error',
          })
        }
      })
  } else {
    if (tableData.value.some((item) => item.name === form.name)) {
      const index = tableData.value.findIndex((item) => item.name === form.name)
      myAxios
        .put('/medicine/update', {
          id: tableData.value[index].id,
          name: form.name,
          categoryId: form.categoryId,
          price: form.price,
          manufacturer: form.manufacturer,
          stock: Number(form.stock) + tableData.value[index].stock,
          expirationDate: form.expirationDate,
        })
        .then((res) => {
          if (res.data.code === 200) {
            ElMessage({
              message: '修改成功',
              type: 'success',
            })
            init()
          } else {
            ElMessage({
              message: '修改失败',
              type: 'error',
            })
          }
        })
    } else {
      myAxios
        .post('/medicine/create', {
          name: form.name,
          categoryId: form.categoryId,
          price: form.price,
          manufacturer: form.manufacturer,
          stock: form.stock,
          expirationDate: form.expirationDate,
          status: '在售',
        })
        .then((res) => {
          if (res.data.code === 200) {
            ElMessage({
              message: '添加成功',
              type: 'success',
            })
            init()
          } else {
            ElMessage({
              message: '添加失败',
              type: 'error',
            })
          }
        })
    }
  }
  form.name = ''
  form.categoryId = ''
  form.categoryName = ''
  form.price = ''
  form.manufacturer = ''
  form.stock = ''
  form.expirationDate = ''
  form.status = ''
  dialogFormVisible.value = false
}
const handleClick = (row) => {
  idForEdit.value = row.id
  form.name = row.name
  form.categoryId = row.categoryId
  form.categoryName = nameOfId.value[row.categoryId]
  form.price = row.price
  form.manufacturer = row.manufacturer
  form.stock = row.stock
  form.expirationDate = row.expirationDate
  form.status = row.status
  isEdit.value = true
  dialogFormVisible.value = true
}

const deleteCategory = (row) => {
  myAxios
    .put(`/medicine/${row.id}/status`, null, {
      params: {
        status: row.status === '在售' ? '停售' : '在售',
      },
    })
    .then((res) => {
      if (res.data.code === 200) {
        ElMessage({
          message: '操作成功',
          type: 'success',
        })
        init()
      } else {
        ElMessage({
          message: '操作失败',
          type: 'error',
        })
      }
    })
}

const init = () => {
  myAxios.get('/category/list').then((res) => {
    if (res.data.code === 200) {
      const records = res.data.data.records // 获取返回的记录数组
      options.value = records.map((item) => ({
        value: item.id, // 每个选项的 value 是 item.id
        label: item.categoryName, // 每个选项的 label 是 item.categoryName
      }))
      const optionsObj: { [key: string]: string } = {}
      records.forEach((item) => {
        optionsObj[item.id] = item.categoryName
      })
      nameOfId.value = optionsObj
      myAxios.get('/medicine/list').then((res) => {
        if (res.data.code === 200) {
          tableData.value = res.data.data.records
          tableData.value.forEach((item) => {
            item.categoryName = nameOfId.value[item.categoryId]
          })
          total.value = tableData.value.length
        }
      })
    }
  })
}

const searchValue = ref('')
const searchButton = () => {
  if (searchValue.value === '') {
    init()
  } else {
    myAxios.get(`/medicine/name/${searchValue.value}`).then((res) => {
      if (res.data.code === 200) {
        const data = [
          {
            id: res.data.data.id,
            name: res.data.data.name,
            categoryId: res.data.data.categoryId,
            categoryName: nameOfId.value[res.data.data.categoryId],
            price: res.data.data.price,
            manufacturer: res.data.data.manufacturer,
            stock: res.data.data.stock,
            expiration_date: res.data.data.expiration_date,
            status: res.data.data.status,
          },
        ]
        tableData.value = data
        total.value = tableData.value.length
      }
    })
  }
}

const exportTable = () => {
  const workbook = new ExcelJS.Workbook()
  const worksheet = workbook.addWorksheet('Sheet1')
  worksheet.columns = [
    { header: '药品名称', key: 'name', width: 10 },
    { header: '药品分类', key: 'categoryName', width: 2010 },
    { header: '药品价格', key: 'price', width: 20 },
    { header: '药品厂家', key: 'manufacturer', width: 20 },
    { header: '药品库存', key: 'stock', width: 20 },
    { header: '药品状态', key: 'status', width: 20 },
  ]
  tableData.value.forEach((rowData) => {
    worksheet.addRow(rowData)
  })
  workbook.xlsx.writeBuffer().then((buffer) => {
    const blob = new Blob([buffer], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = '药品详情.xlsx'
    a.click()
  })
}
onMounted(() => {
  init()
})
</script>
